using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using MSOutlook = Microsoft.Office.Interop.Outlook;
using Utility = Microsoft.Sample.Outlook.Utility;

namespace Microsoft.Sample.Outlook.CRMIntegration.FolderHomePages
{
	[System.Runtime.InteropServices.ComVisible(true)]
	[System.Runtime.InteropServices.Guid("1F2759CB-9A0E-437e-B45E-A2AED6B11B13")]
	public sealed partial class CRMTodayView : UserControl
    {
#if !INSTALL
        //These registration methods are only called when compiling w/ VS
        //For installer scenarios, the RegisterSafeforScripting call is 
        //executed by the installer class

		[System.Runtime.InteropServices.ComRegisterFunction()]
		public static void RegisterServer(Type t)
		{
			Utility.FolderHomePage.RegisterSafeForScripting(t);
		}

		[System.Runtime.InteropServices.ComUnregisterFunction()]
		public static void UnregisterServer(Type t)
		{
			Utility.FolderHomePage.UnregisterSafeForScripting(t);
		}
#endif

        MSOutlook.Application _app = null;

		public void Initialize(MSOutlook.Application o)
		{
			_app = (MSOutlook.Application)o;


		}

		public CRMTodayView()
		{
			InitializeComponent();
			ThisApplication.ConfigureDataDirectory(this.GetType());


		}

		private void CRMTodayView_Load(object sender, EventArgs e)
		{
			labelDateToday.Text = DateTime.Now.ToString("dddd, MMMM dd yyyy");

			try
			{
				accountsSummaryTableAdapter.Fill(crmDataSet.AccountsSummary);
				activitiesSummaryTableAdapter.Fill(crmDataSet.ActivitiesSummary);
				opportunitiesSummaryTableAdapter.Fill(crmDataSet.OpportunitiesSummary);
			}
			catch (Exception ex)
			{
                MessageBox.Show("The CRM Today page couldn't access the database", "Outlook CRM Integration Sample");
                ThisApplication.LogException(ex);
            }

		}

		private void OnAccountClick(object sender, DataGridViewCellEventArgs e)
		{
			if (e.RowIndex == -1)
				return;

			string entryID = (string)gridAccountsSummary.Rows[e.RowIndex].Cells[0].Value;

			if (_app != null)
			{
				MSOutlook.MAPIFolder folder = _app.Session.GetFolderFromID(entryID, System.Reflection.Missing.Value);
				_app.ActiveExplorer().CurrentFolder = folder;
			}
		}

		private void OnItemClick(object sender, DataGridViewCellEventArgs e)
		{
			DataGridView grid = (DataGridView)sender;

			if (e.RowIndex == -1)
				return;

			string entryID = (string)grid.Rows[e.RowIndex].Cells[0].Value;

			if (_app != null)
			{
				object o = _app.Session.GetItemFromID(entryID, System.Reflection.Missing.Value);
				Utility.ItemAdapter item = Utility.ItemAdapter.FromObject(o);
				item.Display();
			}
		}
	}
}
